# -*- coding: utf-8 -*-
from appium import webdriver
import time
import random
import colorsys
from PIL import Image
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


platformName = 'Android' #手机系统

# platformVersion = '9' #安卓版本号
platformVersion = '6.0' #安卓版本号
# adb devices  查看手机安卓号
# 0123456789ABCDEF        device
# SSV4W8JZFU4SLJ6S        device
# deviceName = 'SSV4W8JZFU4SLJ6S'# oppo安卓号
deviceName = '0123456789ABCDEF'# koo安卓号
# deviceName = '0123456789ABCDEF'# koo安卓号

appPackage = 'com.eg.android.AlipayGphone'
appActivity = 'com.eg.android.AlipayGphone.AlipayLogin'
automationName = 'Uiautomator2'
unicodeKeyboard = True
noReset = True


# com.eg.android.AlipayGphone

class AliPay():
    """
    口碑类
    """
    def __init__(self):
        self.desired_caps = {}
        self.desired_caps['platformName'] = platformName
        self.desired_caps['platformVersion'] = platformVersion
        self.desired_caps['deviceName'] = deviceName
        self.desired_caps['appPackage'] = appPackage
        self.desired_caps['appActivity'] = appActivity
        self.desired_caps['noReset'] = noReset
        # self.desired_caps["unicodeKeyboard"] = "True"
        self.desired_caps["resetKeyboard"] = "True"
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_capabilities=self.desired_caps)

        self.wait = WebDriverWait(self.driver, 300)
        self.wait_phone = WebDriverWait(self.driver, 11)
        self.driver.implicitly_wait(11)

    def enter_app_search(self):

        time.sleep(2)
        if self.is_element_exist('android:id/button2'):
            self.driver.find_element_by_id('android:id/button2').click()
        time.sleep(1)
        # 进入支付宝首页面, 点击朋友
        self.driver.find_element_by_id('com.alipay.mobile.socialwidget:id/social_tab_text').click()
        time.sleep(1)
        # 点击右上角加号
        self.driver.find_element_by_id('com.alipay.mobile.socialwidget:id/title_more_menu_button').click()
        time.sleep(1)
        # 出现下拉框, 选择添加朋友
        self.driver.find_element_by_xpath('/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.ListView/android.widget.LinearLayout[2]/android.widget.FrameLayout[2]/android.widget.TextView').click()
        time.sleep(1)

        # 选中输入框
        self.driver.find_element_by_id('com.alipay.mobile.antui:id/search_input_box').click()
        time.sleep(1)

    def is_element_exist(self, element):
        '''
        验证是否存在某个元素
        :param element:
        :return:
        '''
        source = self.driver.page_source
        if element in source:
            return True
        else:
            return False

    def get_image(self, phone):

        add_friend_page = 'com.alipay.mobile.contactsapp.ui.AddFriendActivity_'
        # 获取当前的页面名
        page_name = self.driver.current_activity
        if page_name==add_friend_page:
            # 先清理输入框
            self.driver.find_element_by_id('com.alipay.mobile.ui:id/social_search_normal_input').clear()
            # 输入手机号
            self.driver.find_element_by_id('com.alipay.mobile.ui:id/social_search_normal_input').send_keys(phone)
            time.sleep(1)
            self.driver.find_element_by_id('com.alipay.mobile.contactsapp:id/search_tip_TableView').click()
            time.sleep(1)
            if self.is_element_exist('com.alipay.mobile.antui:id/ensure'):
                # 账号不存在问题
                print('当前号码不存在!')
                with open('账号不存在(未注册).txt', 'a+', encoding='utf-8') as f:
                    f.write(phone.strip())
                    f.write('\n')
                # 点击屏幕中的确定 	com.alipay.mobile.antui:id/ensure  [129,1196][951,1343]
                self.driver.find_element_by_id('com.alipay.mobile.antui:id/ensure').click()
                time.sleep(2)
                self.wait.until(EC.element_to_be_clickable((By.ID, 'com.alipay.mobile.ui:id/social_search_normal_input')))
                self.driver.find_element_by_id('com.alipay.mobile.ui:id/social_search_normal_input').clear()
                return
            else:
                # 手机号码 多账号问题  9WZu22Q$
                if self.is_element_exist('android:id/alertTitle'):
                    self.driver.find_element_by_xpath('/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.widget.ListView/android.widget.RelativeLayout[1]/android.widget.LinearLayout').click()
                else:
                    if self.is_element_exist('com.alipay.mobile.contactsapp:id/search_tip_TableView'):
                        self.driver.find_element_by_id('com.alipay.mobile.contactsapp:id/search_tip_TableView').click()

            time.sleep(1)
        # 获取当前的页面名
        page_name = self.driver.current_activity
        if page_name != 'com.alipay.android.phone.wallet.profileapp.ui.ProfileActivity_':
            return
        # 判断是否未认证
        if self.is_element_exist('未实名'):
            print('未实名认证用户')
            with open('未实名认证.txt', 'a+', encoding='utf-8') as f:
                f.write(phone.strip())
                f.write('\n')
            self.back_()
            return

        if self.is_element_exist('com.alipay.android.phone.wallet.profileapp:id/iv_usergrade'):

            # 进入个人信息界面进行截图
            image_path = r"C:\Users\ZGS\Desktop\herhome\验证PhoneNumber\images\phone-{}.png".format(phone)
            time.sleep(1)
            self.driver.save_screenshot(image_path)
            # 获取会员起止标记, 获取实名认证标记起止坐标, 进行定位截图
            # 会员等级图坐标, 大小
            location1 = self.driver.find_element_by_id('com.alipay.android.phone.wallet.profileapp:id/iv_usergrade').location
            print(location1)
            size1 = self.driver.find_element_by_id('com.alipay.android.phone.wallet.profileapp:id/iv_usergrade').size
            print(size1)
            # 获取实名认证标记识别男女
            # com.alipay.android.phone.wallet.profileapp:id/tv_right
            location2 = self.driver.find_element_by_xpath('//android.widget.TextView[@content-desc="***已实名"]').location
            size2 = self.driver.find_element_by_xpath('//android.widget.TextView[@content-desc="***已实名"]').size
            '''
            [274,917][416,958] 三个字 女 	[274,849][416,890]
            [274,849][416,890] 三个字 男
            '''
            user_info = {"img_path": image_path, "tb_location": location1, "tb_size": size1, "rz_location": location2, "rz_size": size2, "phone": phone}
            print(f"获取到图片图标位置信息: \n{user_info}")
            # 调用图片剪辑
            self.cut_images( user_info=user_info)
            print(f"{phone} 用户信息图已经被截取\n\n")
            # 点击返回查询界面, 并清空输入框
            time.sleep(1)

        self.back_()

    def back_(self):
        # self.driver.press_keycode(keycode=4)
        self.driver.find_element_by_xpath('//android.widget.FrameLayout[@content-desc="返回"]/android.widget.ImageView').click()
        time.sleep(1)
        print('----------------------------')
        # 这里需要判断下是不是已经返回该页面
        # 清空输入框
        self.driver.find_element_by_id('com.alipay.mobile.ui:id/social_search_normal_input').clear()

    def cut_images(self, user_info):

        if isinstance(user_info, dict):
            image_path = user_info["img_path"]
            location = user_info["tb_location"]
            size = user_info["tb_size"]
            location_ = user_info["rz_location"]
            size_ = user_info["rz_size"]
            phone = user_info["phone"]

            # 会员图标
            xs = location['x'] + 3
            ys = location['y'] + 3
            height = size['height']
            width = size['width']
            xe = xs + width - 5
            ye = ys + height -5
            img = Image.open(image_path)
            crop = img.crop((xs, ys, xe, ye))
            tb_path = r'C:\Users\ZGS\Desktop\herhome\验证PhoneNumber\tb\tb.png'
            crop.save(tb_path)

            # 性别图标
            xs = location_['x']
            ys = location_['y']
            height_ = size_['height']
            width_ = size_['width']
            xe = xs + width_
            ye = ys + height_

            img = Image.open(image_path)
            # [274,849][416,890] (142, 41)
            # [274,794][494,835] (220, 41)
            print(f'截图: 开始>{(xs, ys)} 结束>{(xe, ye)}')
            crop = img.crop((xs + 36, ys, xe, ye))
            rz_path = r'C:\Users\ZGS\Desktop\herhome\验证PhoneNumber\tb\rz.png'
            crop.save(rz_path)
            self.image_({"tb_img_path": tb_path, "rz_img_path": rz_path, "phone": phone})

    # 利用pillow模块识别, 图中的颜色, 通过颜色判断是否为女性,黄金会员
    def image_(self, res_dict):
        '''
        输入截图位置, 简单处理
        :param images_path: 截图的path
        :return:
        '''
        tb_img_path = res_dict["tb_img_path"]
        rz_img_path = res_dict["rz_img_path"]
        phone = res_dict["phone"]
        # 打开图
        image1 = Image.open(tb_img_path)
        image2 = Image.open(rz_img_path)
        # 处理
        image1 = image1.convert('RGB')
        image2 = image2.convert('RGB')
        # 调用图片颜色识别得出结果, (1, 1, 1)
        dominant_color_tb = self.get_dominant_color(image1)
        dominant_color_rz = self.get_dominant_color(image2)
        dom_list = [dominant_color_rz, dominant_color_tb]

        self.imput_res(phone, dom_list)

    def imput_res(self, phone, dom):
        '''
        将手机号分类, 普通会员挑出来, 黄金以上会员保留
        :return:
        '''
        tb = dom[0]
        x0 = tb[0]
        x1 = tb[1]
        x2 = tb[2]
        red = (246, 89, 126)
        sex = False
        # 判断性别筛选男女
        if red[0]-30 < x0 < red[0] + 20:
            if red[1]-20 < x1 < red[1] + 20:
                if red[2]-20 < x2 < red[2] + 20:
                    print(f'{phone}>> 经过判断为女性')
                    sex = True

        if sex:
            rz = dom[1]
            x = rz[0]
            y = rz[1]
            z = rz[2]
            bule = (68, 164, 238)

            # 判断会员图标的颜色
            if bule[0]-30 < x < bule[0]+10:
                if bule[1]-30 < y < bule[1]+10:
                    if bule[2]-30 < z < bule[2]+20:
                        print("普通会员")
                        with open(r'普通会员手机号.txt', 'a+', encoding='utf-8') as f:
                            f.write(phone.strip())
                            f.write('\n')
                    else:
                        print('z坐标不通过')
                        with open(r'其他会员手机号.txt', 'a+', encoding='utf-8') as f:
                            f.write(phone.strip())
                            f.write('\n')
                else:
                    print('y坐标不通过')
                    with open(r'其他会员手机号.txt', 'a+', encoding='utf-8') as f:
                        f.write(phone.strip())
                        f.write('\n')
            else:
                print('x坐标不通过')
                with open(r'其他会员手机号.txt', 'a+', encoding='utf-8') as f:
                    f.write(phone.strip())
                    f.write('\n')
        else:
            print(f'{phone}>>男性用户跳过')

    @staticmethod
    def get_dominant_color(image):
        '''
        接收处理过结果, 对图片主颜色进行判断
        :param image:
        :return:
        '''
        max_score = 0.0001
        dominant_color = None
        for count, (r, g, b) in image.getcolors(image.size[0] * image.size[1]):
            # 转为HSV标准
            saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
            y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
            y = (y - 16.0) / (235 - 16)

            # 忽略高亮色
            if y > 0.9:
                continue
            score = (saturation + 0.1) * count
            if score > max_score:
                max_score = score
                dominant_color = (r, g, b)
        return dominant_color


if __name__ == '__main__':
    num = 1
    alp = AliPay()
    alp.enter_app_search()
    print(f'开始验证>>>>>>')
    with open(r'C:\Users\ZGS\Desktop\herhome\验证PhoneNumber\phones\hunhe.txt', 'r', encoding='utf-8') as f1:
        phone_list = f1.readlines()
        for p in phone_list:
            print(f'当前用户手机号: {p}')
            with open(r'C:\Users\ZGS\Desktop\herhome\验证PhoneNumber\验证记录.txt', 'r', encoding='utf-8') as f:
                long_str = f.read()
                if p.strip() in long_str:
                    print(f'{p}已经被爬取过!')
                    continue
                else:
                    print(f'开始验证第{num}个')
                    alp.get_image(p.strip())
                    with open(r'C:\Users\ZGS\Desktop\herhome\验证PhoneNumber\验证记录.txt', 'a+', encoding='utf-8') as f:
                        f.write(p)
                    num += 1
